package com.barradata.app0624.modules.protocol

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.webkit.JavascriptInterface
import android.webkit.WebSettings
import com.barradata.R
import com.barradata.app0624.config.Constant
import com.barradata.app0624.data.UserDataManager
import com.barradata.common.base.BaseActivity
import com.google.gson.Gson
import kotlinx.android.synthetic.main.loan_protocol_activity.*

/**
 * Author:    WuNan
 * Email:     wunan@barradata.com
 * Created:   2019/7/12 16:13
 * Description: 借款协议展示页面
 **/
class LoanProtocolActivity : BaseActivity() {
    companion object {
        private const val LOAN_MONEY_KEY = "LOAN_MONEY_KEY"
        private const val LOAN_PERIOD_KEY = "LOAN_PERIOD_KEY"

        fun actionStart(context: Context, loanMoney: String, loanPeriod: String) {
            val intent = Intent(context, LoanProtocolActivity::class.java)
            intent.putExtra(LOAN_MONEY_KEY, loanMoney)
            intent.putExtra(LOAN_PERIOD_KEY, loanPeriod)
            context.startActivity(intent)
        }
    }

    private var loanMoney: String = ""
    private var loanPeriod: String = ""


    override fun getLayoutId() = R.layout.loan_protocol_activity

    @SuppressLint("SetJavaScriptEnabled")
    override fun initView() {
        fetchData()
        setupActionBar(toolbar)
        setupWebView()
    }

    private fun setupWebView() {
        web_view.loadUrl(Constant.CONTRACT_URL)
        web_view.addJavascriptInterface(this, "jsi")
        web_view.settings.javaScriptEnabled = true
        web_view.settings.cacheMode = WebSettings.LOAD_NO_CACHE
    }

    private fun fetchData() {
        loanMoney = intent.getStringExtra(LOAN_MONEY_KEY)
        loanPeriod = intent.getStringExtra(LOAN_PERIOD_KEY)
    }

    @JavascriptInterface
    fun getOrderInfoData() {
        runOnUiThread {
            val info = HashMap<String, String>()
            info["token"] = UserDataManager.token
            info["borrowMoney"] = loanMoney
            info["borrowDay"] = loanPeriod
            info["userUuid"] = UserDataManager.uuid
            val jsonInfo = Gson().toJson(info)
            val url = "javascript:call_back_getOrderInfoData($jsonInfo)"
            web_view.loadUrl(url)
        }
    }
}